/**
 * Created by chengming on 18/4/18.
 * version 1.0
 */
const BaseAdapter = require('./base/BaseAdapter');
const logger = require('../conf/logger');
const request = require('request-promise');
const cheerio = require('cheerio');
const moment = require('moment');
const urlTool = require('url');
const server = require('../conf/server');
const iconv = require("iconv-lite");
const report = require('../exception/ErrorReport');

class ArticleDetailAdapter extends BaseAdapter{

	constructor(page, isTest, notTime){
		super(page, page.encoding ||'UTF-8', isTest, notTime);
		this.pageTitle = page.pageTitle;
		this.titleRule = page.titleRule;
		this.contentRule = page.contentRule;
		this.source = page.source;
		this.sourceUrl = page.sourceUrl;
		this.sourcetime = page.sourcetime;
		this.channel = page.channel;
		this.cates = page.cates;
	}

	async execute(){
		logger.debug('开始执行抓取');

		let body = await this.doRequest();

		let decodeBody = iconv.decode(body, this.encoding).toString();

		logger.debug('抓取执行完毕,开始分析文本');
		if(!this.contentRule || this.contentRule.length == 0){
			logger.warn('没有内容抓取规则');
			if(this.isTest == false){
				await report(this.sourceUrl, this.source, this.requestUrl,'没有内容抓取规则');
			}
			return {
				code: 411,
				errMsg:'没有内容抓取规则'
			}
		}

		let $ = cheerio.load(decodeBody);

		let title = '缺失标题';
		
		//优先判断如果有标题规则,则直接用标题规则获取到的标题
		if(this.titleRule && this.titleRule.trim().length != 0){
			title = $(this.titleRule).text().trim();
		}else if(this.pageTitle && this.pageTitle.trim().length != 0){
			title = this.pageTitle;
		}else{
			logger.warn('没有标题抓取规则');
			if(this.isTest == false){
				await report(this.sourceUrl, this.source, this.requestUrl,'链接不包含标题,而且没有标题抓取规则');
			}
			return {
				code: 411,
				errMsg:'链接不包含标题,而且没有标题抓取规则'
			}
		}

		let content = $(this.contentRule).html();

		return await super.postSpiderQueue(title, content, this.cates, this.source, this.sourcetime, this.channel);
	}
}

module.exports = ArticleDetailAdapter;